require 'utils'
include Utils

module DataLoader
  
  def load_users(path)
    log = {:loaded => 0, :parse_fail => 0, :users_created => 0}
    f = File.open(path, 'rb')
    
    while line = f.gets do
      line.chomp!
      fields = line.split('|')
      
      if fields.length == 5 then
        User.create(:ff_id => parse_field(fields[0]),
          :ff_type => parse_field(fields[1]),
          :name => parse_field(fields[2]),
          :description => parse_field(fields[4])
        )
        log[:loaded] += 1
      else
        log[:parse_fail] += 1
      end
    end
    
    f.close
    log
  end
  
  def load_services path
    log = {:loaded => 0, :parse_fail => 0}
    f = File.open(path, 'rb')
    
    while line = f.gets do
      line.chomp!
      fields = line.split('|')
      
      if fields.length == 6 then
        ff_id = parse_field(fields[0])
        u = User.find_by_ff_id(ff_id)
        
        if u.nil? then
          u = User.create(:ff_id => ff_id)
          log[:users_created] += 1
        end
        
        u.services.create(:ff_id => parse_field(fields[1]),
          :service_name => parse_field(fields[2]),
          :service_url => parse_field(fields[3]),
          :username_on_service => parse_field(fields[4]),
          :user_url_on_service => parse_field(fields[5]))
        log[:loaded] += 1
      else
        log[:parse_fail] += 1
      end
    end
    
    f.close
    log
  end
  
  module_function :load_users, :load_services
end